//
//  HttpClient.m
//  DebugDemo
//
//  Created by XFB on 2019/5/8.
//  Copyright © 2019 ZhouCheng. All rights reserved.
//

#import "HttpClient.h"
#import "AFNetworking.h"

@interface HttpClient ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation HttpClient

- (instancetype)initWithHandle:(PresenterSuccessCallBack)successBlock
                  failureBlock:(PresenterFailureCallBack)failureBlock
{
    self = [super init];
    if (self) {
        _successBlock = successBlock;
        _failureBlock = failureBlock;
    }
    return self;
}

- (void)get:(NSString *)urlString parameter:(id)parameter
{
    __weak typeof(self) weakSelf = self;
    [self.sessionManager GET:urlString parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (weakSelf.successBlock) {
            weakSelf.successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(error);
        }
    }];
}

- (void)post:(NSString *)urlString parameter:(id)parameter
{
    __weak typeof(self) weakSelf = self;
    [self.sessionManager POST:urlString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (weakSelf.successBlock) {
            weakSelf.successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(error);
        }
    }];
}

- (AFHTTPSessionManager *)sessionManager
{
    if (!_sessionManager) {
        _sessionManager = [AFHTTPSessionManager manager];
        _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    }
    return _sessionManager;
}

@end
